<?php
/**
 * QrCodeScanController.php
 *
 * @copyright   2023 thingsworld.com.cn - All Rights Reserved
 * @link        http://thingsworld.com.cn/
 * @author      stiffer.chen <chenl@thingsworld.com.cn>
 * @created     2023-02-18 02:12:50
 * @modified    2023-02-18 02:12:50
 *
 */

namespace App\Http\Controllers;

use App\Models\CityModel;
use App\Models\Customer;
use App\Models\Customer\User;
use App\Models\Event;
use App\Models\Product;
use App\Models\Product\QrCode;
use App\Repositories\EventRepo;
use App\Services\QrCode\ScanService;
use Illuminate\Http\Request;

class QrCodeScanController extends BaseController
{
    /**
     * @OA\Post(
     *     path="/qrcode_scan/store",
     *     tags={"QrCodeScan"},
     *     summary="二维码扫码数据提交",
     *     description="二维码扫码数据提交",
     *     operationId="qrcode_scan_store",
     *     security={{"bearerAuth":{}}},
     *     @OA\RequestBody(
     *          required=true,
     *          @OA\JsonContent(
     *              type="object",
     *              required={"type", "customer_name", "contact_name", "province_id", "city_id", "county_id", "address", "product_number", "description", "images"},
     *              @OA\Property(property="type", type="string", example="类型(客户报修 或 投诉建议)", description="类型(客户报修 或 意见投诉)"),
     *              @OA\Property(property="customer_name", type="string", example="客户名称", description="客户名称"),
     *              @OA\Property(property="contact_name", type="string", example="联系人姓名", description="联系人姓名"),
     *              @OA\Property(property="province_id", type="integer", example="省份ID", description="省份ID"),
     *              @OA\Property(property="city_id", type="integer", example="城市ID", description="城市ID"),
     *              @OA\Property(property="county_id", type="integer", example="城市ID", description="区县ID"),
     *              @OA\Property(property="address", type="string", example="详细地址", description="详细地址"),
     *              @OA\Property(property="product_number", type="string", example="设备编号", description="设备编号"),
     *              @OA\Property(property="description", type="string", example="描述信息", description="描述信息"),
     *              @OA\Property(
     *                  property="images",
     *                  type="array",
     *                  @OA\Items(),
     *              )
     *          )
     *     ),
     *     @OA\Response(response=200, description="请求成功"),
     *     @OA\Response(response=401,description="鉴权失败"),
     *     @OA\Response(response=422, description="请求异常")
     * )
     */
    public function store(Request $request)
    {
        /**
         * 手机号、联系人名字、客户名字
         * 1、客户找不到 -> customer_id = 0, customer_suer_id = 0
         * 2、客户找到
         *      手机号 当前客户的联系人找到: customer_user_id ≠ 0, 找不到 customer_user_id = 0
         */
        $eventData = request()->getContent();
        $eventArr = json_decode($eventData, true);

        $type = $eventArr['type'] ?? '';
        if (!in_array($type, [EventRepo::TYPE_REPAIR, EventRepo::TYPE_COMPLAIN])) {
            return message('提交类型错误，目前仅支持 客户报修 和 投诉建议', false);
        }

        $customerName = trim($eventArr['customer_name'] ?? '');
        if (!$customerName) {
            return message('请输入客户名称', false);
        }

        $contactName = trim($eventArr['contact_name'] ?? '');
        if (!$contactName) {
            return message('请输入联系人姓名', false);
        }

        $provinceId = intval($eventArr['province_id'] ?? '');

        $cityId = intval($eventArr['city_id'] ?? '');

        $countyId = intval($eventArr['county_id'] ?? '');

        $zones = get_zones($provinceId, $cityId, $countyId);

        $address = trim($eventArr['address'] ?? '');
        if (empty($address)) {
            return message('请填写详细地址', false);
        }

        $productNumber = trim($eventArr['product_number'] ?? '');
        if ($type == EventRepo::TYPE_REPAIR && !$productNumber) {
            return message('请填写设备编号', false);
        }
        $product = Product::byNumber($productNumber)->first();
        $productId = $product->id ?? 0;

        $description = trim($eventArr['description'] ?? '');
        if (empty($description)) {
            if ($type == EventRepo::TYPE_REPAIR) {
                return message('请填写故障现象', false);
            }
            if ($type == EventRepo::TYPE_COMPLAIN) {
                return message('请填写投诉内容', false);
            }
        }

        $eventImages = $eventArr['images'] ?? [];
        $images = [];
        foreach ($eventImages as $eventImage) {
            $images[] = [
                'image' => trim($eventImage)
            ];
        }

        $contactPhone = registry('account');
        $customer = Customer::byName($customerName)->first();
        $customerId = $customerUserId = 0;
        if (empty($customer)) {
            $customerId = $customerUserId = 0;
        } else {
            $customerId = $customer->id;
            $customerUser = User::query()
                ->where('customer_id', $customerId)
                ->where('phone', $contactPhone)
                ->first();
            if (!empty($customerUser)) {
                $customerUserId = $customerUser->id;
            }
        }


        $buyChannel = '';
        $buyDate = '';
        $projectName = '';

        $createdBy = intval($customerUser->id ?? 0);
        $createdType = EventRepo::CREATED_CUSTOMER;

        $main = [
            'event_number' => EventRepo::generateNumber(0),
            'type' => $type,
            'customer_id' => $customerId,
            'customer_name' => $customerName,
            'customer_user_id' => $customerUserId,
            'product_id' => $productId,
            'contact_name' => $contactName,
            'contact_telephone' => $contactPhone,
            'buy_channel' => $buyChannel,
            'buy_date' => $buyDate,
            'project_name' => $projectName,
            'product_number' => $productNumber,
            'province_id' => $zones['province_id'] ?? 0,
            'province_name' => $zones['province_name'] ?? '',
            'city_id' => $zones['city_id'] ?? 0,
            'city_name' => $zones['city_name'] ?? '',
            'county_id' => $zones['county_id'] ?? 0,
            'county_name' => $zones['county_name'] ?? '',
            'address' => $address,
            'description' => $description,
            'created_type' => $createdType,
            'created_by' => $createdBy,
            'status' => EventRepo::STATUS_UN_DISTRIBUTE
        ];

        $data = [
            'main' => $main,
            'images' => $images,
            'users' => []
        ];

        $this->logger->info("store data");
        $this->logger->info($data);

        EventRepo::store(0, $createdBy, $createdType, $data);

        return message('信息提交成功', true);
    }
}